import permissionMgr from '@/biz/user/permission.js'
import secret from '@/common/secretCode.js'
import tool from '@/common/tool.js'
import router from '@/router/index'
import rouetrAdd from '@/router/pageOptions'
import stotr from '@/store'
import { buildPage } from './buildPage.js'
import dt from '@dt/dt'

let routerControl = function () {}

routerControl.prototype.routerChange = function (mess, menuControl) {
  for (let index = mess.length - 1; index >= 0; index--) {
    if (mess[index].meta.noAuthor) continue
    else if (!menuControl.includes(mess[index].meta.permissionCode))
      mess.splice(index, 1)
    else
      mess[index].children &&
        new routerControl().routerChange(mess[index].children, menuControl)
  }
}

export const beginAddRouter = (
  userId,
  roleId,
  flag = true,
  roleType,
  authId
) => {
  if (!userId) return false
  let params = {
    userId,
    roleId,
    roleType
  }
  if (authId) {
    params.authId = authId
  }
  return permissionMgr.update(params).then((res) => {
    let beforeRouterList = tool.deepClone(rouetrAdd)
    let beforeBuildPage = tool.deepClone(buildPage)
    let routerFlag = tool.getStorage('isbuildFlag')

    let oldMenuCode = tool.getStorage('menuControl')
    let oldButtonCode = tool.getStorage('buttonControl')
    let menuCode = secret.Encrypt(JSON.stringify(res.entryMenuCodeList))
    let buttonCode = secret.Encrypt(JSON.stringify(res.buttonMenuCodeList))

    if (
      (oldMenuCode && oldMenuCode != menuCode) ||
      (oldButtonCode && oldButtonCode != buttonCode)
    ) {
      console.log(oldMenuCode, menuCode, oldButtonCode, buttonCode, '权限code')
      router.replace({
        path: '/login'
      })
      return Promise.reject(new Error('权限发生改变'))
    }

    window.sessionStorage.setItem('menuControl', menuCode)
    window.sessionStorage.setItem('buttonControl', buttonCode)

    if (res.entryMenuCodeList.length) {
      setTimeout(function () {
        new routerControl().routerChange(
          beforeRouterList,
          res.entryMenuCodeList
        )
        new routerControl().routerChange(beforeBuildPage, res.entryMenuCodeList)
        window.sessionStorage.setItem(
          'rouList',
          JSON.stringify(beforeRouterList)
        )
        window.sessionStorage.setItem(
          'buildrouList',
          JSON.stringify(beforeBuildPage)
        )

        routerFlag == 'nobuildpage'
          ? new routerControl().routerAdd(beforeRouterList, flag)
          : new routerControl().routerAdd(beforeBuildPage, flag)
      }, 1)
    } else {
      return Promise.reject('菜单权限或按钮权限为空')
    }
    return res
  })
}

// export const beginAddRouter = (userId, roleId, flag = true, callback) => {

//   let params = {
//     userId,
//     roleId
//   }
//   return permissionMgr.update(params).then((res) => {

//     let beforeRouterList = tool.deepClone(rouetrAdd)
//     let beforeBuildPage = tool.deepClone(buildPage)
//     let routerFlag = tool.getStorage("isbuildFlag")
//     window.sessionStorage.setItem('menuControl', secret.Encrypt(JSON.stringify(res
//       .entryMenuCodeList)))
//     window.sessionStorage.setItem('buttonControl', secret.Encrypt(JSON.stringify(res
//       .buttonMenuCodeList)))

//     if (callback) {
//       if (res.entryMenuCodeList.length && res.buttonMenuCodeList.length) {
//         // 登录成功之后进行跳转
//         callback().then(() => {
//           setTimeout(function() {
//             new routerControl().routerChange(beforeRouterList, res
//               .entryMenuCodeList);
//             new routerControl().routerChange(beforeBuildPage, res
//               .entryMenuCodeList);
//             window.sessionStorage.setItem("rouList", JSON.stringify(
//               beforeRouterList))
//             window.sessionStorage.setItem("buildrouList", JSON.stringify(
//               beforeBuildPage))
//             routerFlag == 'nobuildpage' ? new routerControl().routerAdd(
//               beforeRouterList, flag) : new routerControl().routerAdd(
//               beforeBuildPage, flag)
//           }, 1)
//         })
//       } else {
//         return Promise.reject('菜单权限或按钮权限为空')
//       }
//     } else {
//       setTimeout(function() {
//         new routerControl().routerChange(beforeRouterList, res.entryMenuCodeList);
//         new routerControl().routerChange(beforeBuildPage, res.entryMenuCodeList);
//         window.sessionStorage.setItem("rouList", JSON.stringify(beforeRouterList))
//         window.sessionStorage.setItem("buildrouList", JSON.stringify(
//           beforeBuildPage))
//         routerFlag == 'nobuildpage' ? new routerControl().routerAdd(beforeRouterList,
//           flag) : new routerControl().routerAdd(beforeBuildPage, flag)
//       }, 1)
//     }
//     return res
//   })
// }
routerControl.prototype.routerAdd = function (mess, flag) {
  stotr.dispatch('setRouterList', mess)
  setTimeout((_) => {
      if (dt.unlockingMenu('0300000000')) {
        !flag && router.push('/work/workPage')
      } else {
        !flag && router.push('/home/crimeSceneList')
      }
  }, 500)
}

export const routerChecked = (router) => {
  return new Promise(function (resove, reject) {
    let flag = false,
      { name, path, meta } = router

    if (router.name == 'UdealTask') {
      meta.isbuild = tool.getStorage('isbuildFlag')
    }
    // 判断当前是案场菜单（第二页）还是首页菜单（第一页）
    let list =
      meta.isbuild == 'nobuildpage'
        ? JSON.parse(tool.getStorage('rouList'))
        : JSON.parse(tool.getStorage('buildrouList'))
    // 做一个标记存到local 刷新时用
    tool.setStorage({
      isbuildFlag: meta.isbuild
    })
    //更新左侧菜单
    stotr.dispatch('setRouterList', list)
    let routerEach = (mess, father) => {
      mess.map((item) => {
        father && (father = father + '/')
        if ((item.name && item.name == name) || father + item.path == path)
          flag = true
        if (!flag && item.children) {
          routerEach(item.children, item.path)
        }
      })
    }
    routerEach(list)
    flag ? resove() : reject()
  })
}
